package com.gimi.cloud.bbp.client.service.home.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gimi.cloud.bbp.client.service.home.HomePageService;
import com.gimi.cloud.bbp.common.constant.RedisKeyConstant;
import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.JsonUtil;
import com.gimi.cloud.bbp.common.utils.MyBeanUtils;
import com.gimi.cloud.bbp.common.utils.ReflectUtils;
import com.gimi.cloud.bbp.common.utils.StringUtil;
import com.gimi.cloud.bbp.common.utils.reqhead.Response;
import com.gimi.cloud.bbp.commonService.redis.RedisService;
import com.gimi.cloud.bbp.dao.dao.homePage.AdDao;
import com.gimi.cloud.bbp.dao.dao.homePage.ColumnDao;
import com.gimi.cloud.bbp.dao.dao.homePage.MajorAdDao;
import com.gimi.cloud.bbp.dao.dao.mall.MallAppBannerDao;
import com.gimi.cloud.bbp.dao.dao.mall.MallAppBannerGroupDao;
import com.gimi.cloud.bbp.dao.dao.mall.MallAppRecommentDao;
import com.gimi.cloud.bbp.dao.dao.mall.MallAppRecommentGroupDao;
import com.gimi.cloud.bbp.dao.dao.mall.MallAppSpecialDao;
import com.gimi.cloud.bbp.dao.dao.mall.MallAppSpecialGroupDao;
import com.gimi.cloud.bbp.dao.myMapper.core.query.QueryParam;
import com.gimi.cloud.bbp.dto.app.AdDTO;
import com.gimi.cloud.bbp.dto.app.ColumnDTO;
import com.gimi.cloud.bbp.dto.app.MajorAdDTO;
import com.gimi.cloud.bbp.dto.base.BaseDTO;
import com.gimi.cloud.bbp.dto.mall.MallAppBannerDTO;
import com.gimi.cloud.bbp.dto.mall.MallAppBannerGroupDTO;
import com.gimi.cloud.bbp.dto.mall.MallAppRecommentGroupDTO;
import com.gimi.cloud.bbp.dto.mall.MallAppSpecialDTO;
import com.gimi.cloud.bbp.dto.mall.MallAppSpecialGroupDTO;
import com.gimi.cloud.bbp.entity.mall.MallAppBannerGroupEntity;
import com.gimi.cloud.bbp.entity.mall.MallAppRecommentGroupEntity;
import com.github.pagehelper.PageHelper;

/**
 * Created by shazhiwei on 2017/12/27.
 */
@Service
public class HomePageServiceImpl implements HomePageService{
	@Autowired private ColumnDao columnDao;
    @Autowired private AdDao adDao;
    @Autowired private RedisService redisService;
    @Autowired private MajorAdDao majorAdDao;
    
    @Autowired private MallAppBannerGroupDao mallAppBannerGroupDao;
    @Autowired private MallAppBannerDao mallAppBannerDao;
    @Autowired private MallAppRecommentDao mallAppRecommentDao;
    @Autowired private MallAppRecommentGroupDao mallAppRecommentGroupDao;
    @Autowired private MallAppSpecialGroupDao mallAppSpecialGroupDao;
    @Autowired private MallAppSpecialDao mallAppSpecialDao;

    private static Logger logger = LoggerFactory.getLogger(HomePageServiceImpl.class);

    @Override
    public String homePageColumnList() {
        String pageId = "1";
        String redisKey = RedisKeyConstant.APP_HOME_PAGE_PREFIX + "page" + pageId + ":columnLis";
        //从redis获取数据
        String columns = getColumnListFromRedis(redisKey);
        if(!StringUtil.isBlank(columns)){
            return columns;
        }
        //从mysql获取首页数据
        synchronized (this){
            columns = getColumnListFromRedis(redisKey);
            if(StringUtil.isBlank(columns)){
                columns = getColumnListFromMysql(redisKey);
            }
        }
        return columns;
    }

    @Override
    public String homePageMajorAdList() {
        String pageId = "1";
        String redisKey = RedisKeyConstant.APP_HOME_PAGE_PREFIX + "page" + pageId + ":majorAdList";
        //从redis获取数据
        String ads = getMajorAdListFromRedis(redisKey);
        if(!StringUtil.isBlank(ads)){
            return ads;
        }
        //从mysql获取首页数据
        synchronized (this){
            ads = getMajorAdListFromRedis(redisKey);
            if(StringUtil.isBlank(ads)){
                ads = getMajorAdListFromMysql(redisKey);
            }
        }
        return ads;
    }

    @Override
    public List<ColumnDTO> columnList() {
        return columnDao.columnList();
    }

    @Override
    public List<AdDTO> adList(String columnIds) {
        if(StringUtil.isBlank(columnIds)){
            return null;
        }
        return adDao.getListByColumnIds(columnIds);
    }

    /**
     * 从redis获取栏目
     */
    private String getColumnListFromRedis(String redisKey){
        //从redis获取首页数据
        String result = "";
        try{
            result = redisService.get(redisKey);
        }catch (Exception e){
            logger.error("===>从redis获取数据异常");
        }
        return result;
    }

    /**
     * 从mysql获取栏目
     */
    private String getColumnListFromMysql(String redisKey){
        String result = "";
        Response response = new Response();
        //获取可用栏目,获得栏目columnIds
        List<ColumnDTO> columnList = columnList();
        String columnIds = getColumnIds(columnList);
        if(columnIds.length() < 1){
            throw new MsgException(ResponseCodeEnum.APP_COLUMN_ID_NULL);
        }
        //根据columnIds获取广告列表
        List<AdDTO> adList = adList(columnIds);
        if(adList == null || adList.size() == 0){
            throw new MsgException(ResponseCodeEnum.APP_AD_ID_NULL);
        }
        //将广告塞到栏目dto的广告list中
        for(ColumnDTO column : columnList){
            List<AdDTO> list = new ArrayList<>();
            for (AdDTO ad : adList){
                if(column.getColumnId() == ad.getColumnId()){
                    list.add(ad);
                }
            }
            column.setAdList(list);
        }
        response.setResponseCode(ResponseCodeEnum.SUCCESSED);
        response.setRes_data(columnList);
        result = JsonUtil.toJson(response);
        try {
            redisService.set(redisKey,result);
        }catch (Exception e){
            logger.error("===>redis保存数据异常");
        }
        return result;
    }

    /**
     * 从redis获取推广列表
     */
    private String getMajorAdListFromRedis(String redisKey){
        //从redis获取首页数据
        String result = "";
        try{
            result = redisService.get(redisKey);
        }catch (Exception e){
            logger.error("===>从redis获取数据异常");
        }
        return result;
    }

    /**
     * 从mysql获取推广列表
     */
    private String getMajorAdListFromMysql(String redisKey){
        Response response = new Response();
        String result = "";
        Map<String,Object> data = new HashMap<>();
        List<MajorAdDTO> majorAdList = majorAdDao.getList();
        List<MajorAdDTO> bannerList = new ArrayList<>();
        List<MajorAdDTO> normalList = new ArrayList<>();
        if(majorAdList != null && majorAdList.size() > 0){
            for(MajorAdDTO dto : majorAdList){
                if(dto.getType() == 1){
                    bannerList.add(dto);
                }else if(dto.getType() == 2){
                    normalList.add(dto);
                }
            }
        }
        data.put("bannerList",bannerList);
        data.put("majorAdList",normalList);
        response.setResponseCode(ResponseCodeEnum.SUCCESSED);
        response.setRes_data(data);
        result = JsonUtil.toJson(response);
        if(bannerList.size() > 0 && normalList.size() > 0){
            try{
                redisService.set(redisKey,result);
            }catch (Exception e){
                logger.error("===>保存redis异常");
            }
        }
        return result;
    }

    private String getColumnIds(List<ColumnDTO> columnList){
        StringBuilder result = new StringBuilder();
        if(columnList != null && columnList.size() > 0){
            for(ColumnDTO dto : columnList){
                result.append(dto.getColumnId()).append(",");
            }
            if(result.length() > 0){
                result.delete(result.length() -1,result.length());
            }
        }
        return result.toString();
    }

	@Override
	public Response getHomePageCarouselFigure(BaseDTO params) {
		Response response = new Response(ResponseCodeEnum.SUCCESSED);
		MallAppBannerGroupDTO bannerGroup = mallAppBannerGroupDao.selectOneByNow();
        MallAppBannerDTO bannerDTO = new MallAppBannerDTO();
        ReflectUtils.copyPropertiesIgnoreNullAndEmptyStr(params,bannerDTO);
        bannerDTO.setBrpStatus(1);
        bannerDTO.setAbgId(bannerGroup.getAbgId());
		bannerGroup.setMallAppBanners(this.queryBannerListByParams(bannerDTO));
		Map<String, Object> map = new HashMap<>();
		map.put("bannerGroup", bannerGroup);
		response.setRes_data(map);
		return response;
	}

	@Override
	public Response getHomePageData(BaseDTO params) {
        Response response = new Response(ResponseCodeEnum.SUCCESSED);
        MallAppBannerGroupDTO bannerGroup = mallAppBannerGroupDao.selectOneByNow();
        MallAppBannerDTO bannerDTO = new MallAppBannerDTO();
        ReflectUtils.copyPropertiesIgnoreNullAndEmptyStr(params,bannerDTO);
        bannerDTO.setBrpStatus(1);
        bannerDTO.setAbgId(bannerGroup.getAbgId());
        bannerGroup.setMallAppBanners(this.queryBannerListByParams(bannerDTO)); 

		Map<String, Object> map = new HashMap<>();
		map.put("bannerGroup", bannerGroup);
		response.setRes_data(map);
		return response;
	}

    @Override
    public List<MallAppBannerDTO> queryBannerListByParams(MallAppBannerDTO dto) {
        String sql = "SELECT ban.* FROM mall_app_banner ban WHERE ban.is_delete = 0 AND ban.abg_id = :abgId AND ban.brp_status = :brpStatus ORDER BY ban.brp_sort";
        QueryParam param = new QueryParam();
        param.setSql(sql);
        param.setParamObject(dto);
        return mallAppBannerDao.selectListDTOBySql(param);
    }
    
    @Override
    @Transactional
    public MallAppBannerGroupDTO getBanner(MallAppBannerDTO dto) {
    	List<MallAppBannerGroupEntity> bannerGroupEntitys = mallAppBannerGroupDao.selectNowStartLimit2();
    	MallAppBannerGroupDTO entity = new MallAppBannerGroupDTO();
    	if (bannerGroupEntitys == null || bannerGroupEntitys.isEmpty()) {
    		entity = mallAppBannerGroupDao.selectAlfter();
    		if (entity == null) {
    			return null;
    		}
    		entity.setMallAppBanners(mallAppBannerDao.getBannerByAbgId(entity.getAbgId()));
    		return entity;
    	}
    	//如果第一个是没有开始的，着这是一个未新的首页，结束上一个首页
    	if (bannerGroupEntitys.get(0).getAbgStartTime() == null) {
    		bannerGroupEntitys.get(0).setAbgStartTime(new Date());
    		mallAppBannerGroupDao.baseUpdateByPrimaryKey(bannerGroupEntitys.get(0));
    		//第一次获取可能只有一条记录
    		if (bannerGroupEntitys.size() > 1) {
    			bannerGroupEntitys.get(1).setAbgEndTime(new Date());
        		mallAppBannerGroupDao.baseUpdateByPrimaryKey(bannerGroupEntitys.get(1));
    		}
    	} 
    	MyBeanUtils.copyPropertiesIgnoreNullAndEmptyStr(bannerGroupEntitys.get(0), entity);
    	entity.setMallAppBanners(mallAppBannerDao.getBannerByAbgId(entity.getAbgId()));
    	return entity;
    }
    
    @Override
    @Transactional
    public MallAppRecommentGroupDTO getRecomment(MallAppRecommentGroupDTO dto) {
    	List<MallAppRecommentGroupEntity> recommentGroupEntity = mallAppRecommentGroupDao.selectNowStartLimit2();
    	MallAppRecommentGroupDTO entity = new MallAppRecommentGroupDTO();
    	if (recommentGroupEntity == null || recommentGroupEntity.isEmpty()) {
    		entity = mallAppRecommentGroupDao.selectAlfter();
    		if (entity == null) {
    			return null;
    		}
    		entity.setMallAppRecomments(mallAppRecommentDao.getRecommentByArgId(entity.getArgId()));
    		return entity;
    	}
    	//如果第一个是没有开始的，着这是一个未新的首页，结束上一个首页
    	if (recommentGroupEntity.get(0).getArgStartTime() == null) {
    		recommentGroupEntity.get(0).setArgStartTime(new Date());
    		mallAppRecommentGroupDao.baseUpdateByPrimaryKey(recommentGroupEntity.get(0));
    		//第一次获取可能只有一条记录
    		if (recommentGroupEntity.size() > 1) {
    			recommentGroupEntity.get(1).setArgEndTime(new Date());
    			mallAppRecommentGroupDao.baseUpdateByPrimaryKey(recommentGroupEntity.get(1));
    		}
    	} 
    	MyBeanUtils.copyPropertiesIgnoreNullAndEmptyStr(recommentGroupEntity.get(0), entity);
    	entity.setMallAppRecomments(mallAppRecommentDao.getRecommentByArgId(entity.getArgId()));
    	return entity;
    }
    
    @Override
    @Transactional
    public List<MallAppSpecialGroupDTO> getSpecial(MallAppSpecialGroupDTO dto) {
    	List<MallAppSpecialGroupDTO> appSpecialGroupEntities = mallAppSpecialGroupDao.selectNowStart();
    	if (appSpecialGroupEntities == null || appSpecialGroupEntities.isEmpty()) {
    		return null;
    	}
    	mallAppSpecialGroupDao.updateStartTimeByNow();
    	mallAppSpecialGroupDao.updateEndTimeByNow();
    	return appSpecialGroupEntities;
    }
    
    @Override
    public MallAppSpecialGroupDTO getSpecialListByAsgId(MallAppSpecialDTO dto) {
    	MallAppSpecialGroupDTO appSpecialGroupEntitie = mallAppSpecialGroupDao.selectDTOByAsgId(dto.getAsgId());
    	PageHelper.startPage(dto.getPageNums(), dto.getPageSizes());
    	appSpecialGroupEntitie.setSpecials(mallAppSpecialDao.getDTOByAsgId(dto.getAsgId()));
		return appSpecialGroupEntitie;
    }
    
   
    
    
}
